package org.mili.ticketeer.service;

import org.mili.ticketeer.dao.DaoFactory;
import org.mili.ticketeer.dao.MeetingDao;
import org.mili.ticketeer.dao.RowTransformer;
import org.mili.ticketeer.dao.query.v2.QueryBuilder;
import org.mili.ticketeer.dto.Contact;
import org.mili.ticketeer.dto.Meeting;
import org.mili.ticketeer.util.Lambda;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

public class MeetingService extends Service {
	private MeetingDao _meetingDao = DaoFactory.getDao(MeetingDao.class);

    public Boolean assign(final Contact contact, final int date) throws ServiceException {
        return doInService(new Lambda<Boolean>() {
            @Override
            public Boolean exec(Object... params) throws Exception {
                return _meetingDao.assign(contact, date);
            }
        });
    }

    public List<Meeting> getVisitedMeetingsFor(final Contact contact, final int year) throws ServiceException {
        List<Meeting> list = doReadInService(new Lambda<List<Meeting>>() {
            @Override
            public List<Meeting> exec(Object... params) throws Exception {
                return _meetingDao.read(new RowTransformer<Meeting>() {
                    @Override
                    public Meeting transform(ResultSet resultSet) throws SQLException {
                        Meeting meeting = new Meeting();
                        meeting.setDate(resultSet.getInt(Meeting.Fields.DATE.name()));
                        meeting.setContact(contact.getId());
                        return meeting;
                    }
                }, QueryBuilder.createQueryBuilder().select().fields(Meeting.Fields.values()).from(Meeting.TABLE)
                        .where().eq(Meeting.Fields.CONTACT, contact.getId()).build());
            }
        });
        for (int i = list.size() - 1; i >= 0; i --) {
            Meeting meeting = list.get(i);
            if (!String.valueOf(meeting.getDate()).startsWith(String.valueOf(year))) {
                list.remove(i);
            }
        }
        return list;
    }
}
